import base64
import urllib.parse
from selenium.webdriver.chrome.service import Service
from selenium import webdriver
from loguru import logger

logger.add("tool.log", retention="3 days")


# chromedriver 下载页
# http://chromedriver.storage.googleapis.com/index.html
#

class BrowserTool:
    @logger.catch
    def __init__(self):
        self.path = Service('chromedriver.exe')
        self.browser = webdriver.Chrome(service=self.path)

    def isRun(self):
        object_existed = False
        if self.browser is not None:
            try:
                self.browser.execute_script('javascript:void(0);')
                object_existed = True
            except:
                try:
                    self.browser.quit()
                finally:
                    self.browser = None
            finally:
                pass
        return object_existed

    @logger.catch
    def show(self, file):
        file_path = 'http://127.0.0.1:8000/' + file
        url = 'http://127.0.0.1:8012/onlinePreview?url=' + urllib.parse.quote(
            base64.b64encode(file_path.encode("utf-8")))
        if not self.isRun():
            logger.info("浏览器已关闭，重新启动")
            self.browser = webdriver.Chrome(service=self.path)
        self.browser.get(url)
        self.browser.execute_script('document.title = "' + file.split("/")[-1] + '"')

    def close(self):
        self.browser.close()


if __name__ == '__main__':
    browser = BrowserTool()
    file_url = '云计算实验报告-张三.docx'
    browser.show(file_url)
